import qs from 'qs'
import axios from 'axios'
import DuUtil from '../DuUtil'

export function useRequest() {
  // 用来存储正在发起的请求
  const requestMap = new Map()

  const CancelToken = axios.CancelToken
  const source = CancelToken.source()

  // 根据请求的config，生成一个专属的key
  function generateReqKey(config) {
    const { method, url, params, data } = config
    let paramsStr = ''
    if (DuUtil.isString(params)) {
      paramsStr = qs.stringify(JSON.parse(params))
    } else {
      paramsStr = params ? qs.stringify(params) : ''
    }

    let dataStr = ''
    if (DuUtil.isString(data)) {
      dataStr = qs.stringify(JSON.parse(data))
    } else {
      dataStr = data ? qs.stringify(data) : ''
    }

    return [method, url, paramsStr, dataStr].join('&')
  }

  // 取消当前的请求
  function ifCancelCurrentReq(config) {
    const requestkey = generateReqKey(config)
    // 如果requestMap存在当前请求，则取消当前请求
    if (requestMap.has(requestkey)) {
      config.cancelToken = source.token
      source.cancel('取消请求')
      return true
    } else {
      return false
    }
  }

  // 添加到requestMap中
  function addRequestMap(config) {
    const requestkey = generateReqKey(config)
    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        if (!requestMap.has(requestkey)) {
          requestMap.set(requestkey, cancel)
          console.log('set ', requestkey)
        }
      })
  }

  // 从requestMap中移除
  function removeRequestMap(config) {
    const requestkey = generateReqKey(config)
    if (requestMap.has(requestkey)) {
      requestMap.delete(requestkey)
      console.log('delete ', requestkey)
    }
  }

  // 清除requestMap
  function clearRequestMap() {
    requestMap.clear()
  }

  return {
    requestMap,
    ifCancelCurrentReq,
    addRequestMap,
    removeRequestMap,
    clearRequestMap,
  }
}
